package com.bigfreakindeals.Protocols.SoapHandlers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.sax.*;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import android.util.Xml;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.ClosestSchoolListener;
import com.bigfreakindeals.Models.BarCouponItem;
import com.bigfreakindeals.Models.Branch;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Models.Coupons;
import com.bigfreakindeals.Models.UniversityDeals;
import com.bigfreakindeals.Models.UserProfile;

public class MyCouponsHandler  {

	// names of the XML tags
	 static final String  PARENT = "deals_coupons";
	   
    static final String  ID = "id_deal";
    static final String STATUS = "status";
    static final  String NAME = "name";
    static final  String DESCR = "description";
    static final  String PURC_DATE = "purchase_date";
    static final  String COUPONS_PURCH = "coupons_purchased";

    static final  String TOTAL_COUNT= "total_count";
    static final  String COUPONS_USED = "coupons_used";
    static final  String COUPONS_REMAINING = "coupons_remaining";
    static final  String COUPONS_EXPIRY = "coupons_expired";
    static final  String COUPONS_EXPIRYDATE = "coupon_expiry_date";
    static final  String THUMBNAIL_SMALL = "small_image_url";
    static final  String THUMBNAIL_MED = "medium_image_url";
    static final  String THUMBNAIL_LAR = "large_image_url";
    static final  String FINEPRINT = "fineprint";
    static final  String INSTRUCTION = "instructions";
    
    static final  String COUPONS_BARCODE = "barcode_url";
    static final  String COUPONS_CODE = "coupon_code";
    static final  String COUPONS_ID = "unique_coupon_code";
    static final  String COUPONS_ISUSED= "is_used";
    
    
   
    static final String COMPANY = "company";
    static final String COMPANY_ID = "company_id";
    static final String COMPANY_NAME = "company_name";
    static final String COMPANY_SLUG = "company_slug";
    static final String COMPANY_ADD1 = "company_address1";
    static final String COMPANY_ADD2 = "company_address2";
    static final String COMPANY_PHONE = "company_phone";
    static final String COMPANY_ZIP = "company_zip";
    static final String COMPANY_CITYNAME = "company_city_name";
    static final String COMPANY_STATENAME = "company_state_name";
    static final String COMPANY_LAT = "company_latitude";
    static final String COMPANY_LONG = "company_longitude";
    static final String COMPANY_URL = "company_url";
    static final String COMPANY_BRANCH = "company_branch_offices";
 
    static final String COMPANY_BRANCH_ITEMm = "item";
    static final String COMPANY_BRANCH_ADD1 = "address1";
    static final String COMPANY_BRANCH_PHONE = "phone";
    static final String COMPANY_BRANCH_ZIP = "zip";
    static final String COMPANY_BRANCH_CITYNAME = "city_name";
    static final String COMPANY_BRANCH_STATENAME = "company_state_name";
    static final String COMPANY_BRANCH_LAT = "latitude";
    static final String COMPANY_BRANCH_LONG = "longitude";
    static final String COMPANY_BRANCH_URL = "url";
   
    
    
    
    static final  String ERROR = "error";
    UniversityDeals closestUniversity = new UniversityDeals();
    String feedUrl;
    
    
    private static final String SOAP_ACTION = "1";
    private static final String METHOD_NAME = "bigfreakindeals";
    private static final String NAMESPACE = "1";
	
    public MyCouponsHandler(String feedUrl) {
    	this.feedUrl = feedUrl;
    	parse();
    	
    }

    
    
    public void parse() {
    	System.out.println("parserMYCouponsHandler"+feedUrl);
    	ArrayList<Coupons> ListmyCoupons = new ArrayList<Coupons>();

		try {

			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);

			HttpTransportSE androidHttpTransport = new HttpTransportSE(feedUrl);

			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject response = (SoapObject) envelope.getResponse();

			String status = response.getProperty(STATUS).toString();
			
			if (status != null && status.length() > 0) {
				if (status.contentEquals("false")) {
					// error on active deals
					// get error message

					// TODO ERROR HANDLING
					Intent intent = new Intent(Constant.EVENTS_NOCOUPONSLIST);
					intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, "You have no available coupons.");
					ApplicationEx.getInstance().sendBroadcast(intent);
					return;

				} else {// status = true; active deals exist
				
					
					Vector mycouponsList = (Vector) response.getProperty(PARENT);
					
					Coupons coupon;
					
				
					for (int count = 0; count <= mycouponsList.size() - 1; count++) {

						SoapObject deals = (SoapObject) mycouponsList.get(count);
						coupon = new Coupons();
						
						if (deals.getProperty(ID) != null && (deals.getProperty(ID).toString()).length() > 0)
							coupon.dealID = deals.getProperty(ID).toString();

						if (deals.getProperty(NAME) != null){
							coupon.dealname = deals.getProperty(NAME).toString()+" "+count;
						}
						
						if (deals.getProperty(DESCR) != null){
								
						}
						
						if (deals.getProperty(PURC_DATE) != null){
							
							coupon.purchase_date =  deals.getProperty(PURC_DATE).toString();
						}
						
						if (deals.getProperty(COUPONS_PURCH) != null){
							coupon.coupons_purchased = deals.getProperty(COUPONS_PURCH).toString();
						}
						
						
						if (deals.getProperty(TOTAL_COUNT) != null){
							
							coupon.total_count = deals.getProperty(TOTAL_COUNT).toString();
						}
						
						
						if (deals.getProperty(COUPONS_USED) != null){
							coupon.coupons_used = deals.getProperty(COUPONS_USED).toString();
												}
						if (deals.getProperty(COUPONS_REMAINING) != null){
							
							coupon.coupons_remaining= deals.getProperty(COUPONS_REMAINING).toString();
						}
						
						if (deals.getProperty(COUPONS_EXPIRY) != null){
							
							coupon.coupons_expired = deals.getProperty(COUPONS_EXPIRY).toString();
						}
						if (deals.getProperty(COUPONS_EXPIRYDATE) != null){
							
							coupon.coupons_expirydate = deals.getProperty(COUPONS_EXPIRYDATE).toString();
						}
						if (deals.getProperty(THUMBNAIL_SMALL) != null){
							
							coupon.thumbnailsmall_URL = deals.getProperty(THUMBNAIL_SMALL).toString();
						}
						
						if (deals.getProperty(THUMBNAIL_MED) != null){
							
							coupon.thumbnailmedium_URL = deals.getProperty(THUMBNAIL_MED).toString();
						}
						
						if (deals.getProperty(THUMBNAIL_LAR) != null){
							
							coupon.thumbnaillarge_URL = deals.getProperty(THUMBNAIL_LAR).toString();
						}
						
						if (deals.getProperty(FINEPRINT) != null){
							
							coupon.fineprint = deals.getProperty(FINEPRINT).toString();
						}
						
						if (deals.getProperty(INSTRUCTION) != null){
							
							coupon.instructions = deals.getProperty(INSTRUCTION).toString();
						}
						
						
						
						
						SoapObject companyObj = (SoapObject) deals.getProperty(COMPANY);
						
						if (companyObj!=null){
							Company com = new Company();
							System.out.println("company name"+companyObj);
							if (companyObj.getProperty(COMPANY_ADD1) !=null){
								com.setCompanyAddress1(companyObj.getProperty(COMPANY_ADD1).toString());
							}
							
							if (companyObj.getProperty(COMPANY_ADD2) !=null){
								com.setCompanyAddress2(companyObj.getProperty(COMPANY_ADD2).toString());
								System.out.println("company address2"+com.getCompanyAddress2());;
								
							}
							
							
							if (companyObj.getProperty(COMPANY_NAME) !=null){
								com.setCompanyname(companyObj.getProperty(COMPANY_NAME).toString());
								System.out.println("company name"+companyObj.getProperty(COMPANY_NAME).toString());
								
							}
							
							
							if (companyObj.getProperty(COMPANY_CITYNAME) !=null){
								com.setCityname(companyObj.getProperty(COMPANY_CITYNAME).toString());
							}
							
							if (companyObj.getProperty(COMPANY_SLUG) !=null){
								com.setCompanyslug(companyObj.getProperty(COMPANY_SLUG).toString());
							}
							
							if (companyObj.getProperty(COMPANY_LAT) !=null){
								com.setLatitude(companyObj.getProperty(COMPANY_LAT).toString());
							}
							
							
							if (companyObj.getProperty(COMPANY_LONG) !=null){
								com.setLongitude(companyObj.getProperty(COMPANY_LONG).toString());
							}
							System.out.println("COMPANY_STATENAME");
							if (companyObj.getProperty(COMPANY_STATENAME) !=null){
								com.setStatename(companyObj.getProperty(COMPANY_STATENAME).toString());
								System.out.println("COMPANY_STATENAME"+com.getStatename());
								
							}
							
							if (companyObj.getProperty(COMPANY_ZIP) !=null){
								com.setZip(companyObj.getProperty(COMPANY_ZIP).toString());
							}
							
							if (companyObj.getProperty(COMPANY_URL) !=null){
								com.setWebSite(companyObj.getProperty(COMPANY_URL).toString());
							}
							
							if (companyObj.getProperty(COMPANY_PHONE) !=null){
								com.setPhoneNumber(companyObj.getProperty(COMPANY_PHONE).toString());
							}
							
						
							Vector branchlist = (Vector) companyObj.getProperty("company_branch_offices");
							
							for (int index = 0; index <= branchlist.size() - 1; index++) 
							{

								SoapObject branchItems = (SoapObject) branchlist.get(index);
								
								
								Branch branch = new Branch();
								
								
									if (branchItems.getProperty("address1") != null)
										branch.setCompanyAddress1(branchItems.getProperty("address1").toString());
									
									if (branchItems.getProperty("address2") != null)
										branch.setCompanyAddress2(branchItems.getProperty("address2").toString());
									
									if (branchItems.getProperty("phone") != null)
										branch.setPhoneNumber(branchItems.getProperty("phone").toString());
									
									if (branchItems.getProperty("zip") != null)
										branch.setPhoneNumber(branchItems.getProperty("zip").toString());
										
									if (branchItems.getProperty("city_name") != null)
										branch.setCityname(branchItems.getProperty("city_name").toString());
										
									if (branchItems.getProperty("latitude") != null)
										branch.setLatitude(branchItems.getProperty("latitude").toString());
										
									if (branchItems.getProperty("longitude") != null)
										branch.setLongitude(branchItems.getProperty("longitude").toString());
										
									if (branchItems.getProperty("company_state_name") != null)
										branch.setStatename(branchItems.getProperty("company_state_name").toString());
										
									if (branchItems.getProperty("url") != null)
										branch.setWebSite(branchItems.getProperty("url").toString());
										
								
								com.addBranchOffice(branch);
							}

							 
							System.out.println("branchlist branchItems branchObj "+com.getBranchCount());
							
							
							coupon.company = com;
						}//end for compamy
						
						System.out.println("Step1");
						
						Vector myCouponCode = (Vector) deals.getProperty("coupons");
						System.out.println("Step2"+myCouponCode.size());
							
						for (int i = 0; i < myCouponCode.size(); i++) {
							
						SoapObject item = (SoapObject) myCouponCode.get(i);
						System.out.println("Step3"+item);
						
							if (item!=null){
								if (coupon.barCoupons==null)
									coupon.barCoupons = new ArrayList<BarCouponItem>();
								
								BarCouponItem barcouponItem = new BarCouponItem();
								
								if (item.getProperty(COUPONS_BARCODE) !=null){
									barcouponItem.barCodeString = item.getProperty(COUPONS_BARCODE).toString();
								}
								if (item.getProperty(COUPONS_CODE) !=null){
									barcouponItem.couponCode = item.getProperty(COUPONS_CODE).toString();
								}
								if (item.getProperty(COUPONS_ID) !=null){
									barcouponItem.couponID = item.getProperty(COUPONS_ID).toString();
								}
								if (coupon.barCoupons==null)
									coupon.barCoupons = new ArrayList<BarCouponItem>();
								
								System.out.println("COUPONS BEFORE"+coupon.barCoupons.size());
								coupon.barCoupons.add(barcouponItem);								
								System.out.println("COUPONS AFTER"+coupon.barCoupons.size());
								
							}//and if item
						}//end if couponsObj	
						
						
						// add school to list
						ListmyCoupons.add(coupon);
						
					}// end for

				}

			}

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			System.out.println("EXCEPTION!1"+e1.getMessage());
			Intent intent = new Intent(Constant.EVENTS_NOCOUPONSLIST);
			intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, "You have no available coupons.");
			ApplicationEx.getInstance().sendBroadcast(intent);
			return;
		} catch (Exception e1) {
			System.out.println("EXCEPTION!2"+e1.getMessage());
			Intent intent = new Intent(Constant.EVENTS_NOCOUPONSLIST);
			intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, "You have no available coupons.");
			ApplicationEx.getInstance().sendBroadcast(intent);
			return;
		}
	
		System.out.println("branchlist branchItems branchObj"+ListmyCoupons.size());
		

		if (ListmyCoupons != null && ListmyCoupons.size() > 0) {
			
			
			ApplicationEx.getInstance().myProfile.myCoupons = ListmyCoupons.toArray(new Coupons[]{});
			
			Intent intent = new Intent(Constant.EVENTS_MYCOUPONSLIST);
			ApplicationEx.getInstance().sendBroadcast(intent);
			
		} else { // no school avail
			// TODO ERROR HANDLING
			Intent intent = new Intent(Constant.EVENTS_NOCOUPONSLIST);
			intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, "You have no available coupons.");
			ApplicationEx.getInstance().sendBroadcast(intent);

		}

		// return closestUniversity;
	}



}

